<template>
  <div class="container">
    <el-tabs v-model="activeName"  :stretch="true"   @tab-click="handleClick" >
      <el-tab-pane label="数据库日志" name="0">
        <data-view
          ref="sysLog"
          propViewKey="sys_log"
          propViewForm="sys/log/detail.vue"
        />
      </el-tab-pane>
      <el-tab-pane label="文件日志" name="1">
        <h5 style="text-align: left; padding-left: 8.33333%">显示所配置的logpath下的日志文件列表，日志文件总数：{{logFiles.length}}(目前仅支持10兆以内的日志预览)</h5>
        <el-row>
          <el-col :span="2" style="text-align: center; ">
            <h4 v-if="yearList.length == 0 ">暂无</h4>
            <el-menu class="el-menu-vertical-demo"
                     background-color="#eee"
                     text-color="#000"
                     active-text-color="#3a8ee6"
                     v-else
            >
              <el-menu-item :index="year" v-for="year in yearList" :key="year"  @click="getLogFiles(true, year)">{{year}}</el-menu-item>
            </el-menu>
          </el-col>
          <el-col :span="22" style="padding-left: 11px">
            <el-form :inline="true" :model="formInline" size="medium " >
              <el-form-item label="文件名">
                <el-input v-model="formInline.name" placeholder="回车模糊搜索"  @keyup.native.enter="getLogFiles(true)" clearable></el-input>
              </el-form-item>
              <el-form-item label="日志类型" >
                <el-select v-model="formInline.type" placeholder="请选择" @change="getLogFiles(true)" clearable>
                  <el-option label="请选择" value=""></el-option>
                  <el-option label="debug" value="debug"></el-option>
                  <el-option label="info" value="info"></el-option>
                  <el-option label="warn" value="warn"></el-option>
                  <el-option label="error" value="error"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="reset" >重置</el-button>
              </el-form-item>
            </el-form>

            <el-table
              size="small"
              :header-cell-style="{'text-align':'center'}"
              stripe
              border
              :height="windowHeight-300"
              :default-sort = "{prop: 'lastModified', order: 'descending'}"
              :data="logFiles"
              style="width: 100%">
              <el-table-column
                align="center"
                type="index" >
              </el-table-column>
              <el-table-column
                align="left"
                prop="name"
                sortable
                label="文件名" >
              </el-table-column>
              <el-table-column
                align="left"
                prop="size"
                sortable
                width="150"
                label="文件大小(M：兆)" >
              </el-table-column>
              <el-table-column
                align="left"
                prop="lastModified"
                sortable
                width="180"
                label="最后修改日期" >
              </el-table-column>
              <el-table-column
                align="center"
                prop="type"
                sortable
                label="日志类型"
                width="180">
              </el-table-column>
              <el-table-column
                align="left"
                label="操作"
                width="180">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary"  @click="btnOp(1,scope.row)" >下载</el-button>
                  <el-button size="mini" type="primary"  @click="btnOp(2,scope.row)" v-if="scope.row.size <= 10" >查看</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>
    </el-tabs>

    <!--日志预览-->
    <el-drawer
      :title="dialogTitle"
      :visible.sync="dialogShow"
      direction="rtl"
      @opened="dialogOpened"
      size="90%">
      <div style="padding: 5px 11px 0px 11px;">
        <div style="margin-bottom: 11px; ">
          <el-button @click="dialogShow = false">关闭窗口</el-button>
          <span style="padding-left: 22px ; font-weight: bold;">将光标聚焦到下方容器，ctrl+f 搜索。或者使用浏览器搜索</span>
        </div>
        <div :style="{overflow: 'auto',maxHeight: windowHeight - 100 + 'px'} ">
          <codemirror   ref="logText" v-model="logText" :options="editOptions"  ></codemirror>
        </div>
      </div>

    </el-drawer>
  </div>
</template>

<script>
/*eslint-disable*/
import { codemirror } from 'vue-codemirror'
import 'codemirror/mode/javascript/javascript.js'
import 'codemirror/theme/monokai.css'
import'codemirror/addon/selection/active-line.js'
import'codemirror/addon/selection/mark-selection.js'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/hint/show-hint.js'
import'codemirror/addon/hint/show-hint.css'
import'codemirror/addon/hint/javascript-hint.js'
import'codemirror/addon/selection/active-line.js'
import'codemirror/addon/scroll/annotatescrollbar.js'
import'codemirror/addon/search/matchesonscrollbar.js'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/match-highlighter.js'
import'codemirror/mode/clike/clike.js'
import'codemirror/addon/edit/matchbrackets.js'
import'codemirror/addon/comment/comment.js'
import'codemirror/addon/dialog/dialog.js'
import'codemirror/addon/dialog/dialog.css'
import'codemirror/addon/search/searchcursor.js'
import'codemirror/addon/search/search.js'
import'codemirror/keymap/sublime.js'
import'codemirror/addon/fold/foldgutter.css'
import'codemirror/addon/fold/brace-fold.js'
import'codemirror/addon/fold/comment-fold.js'
import'codemirror/addon/fold/foldcode.js'
import'codemirror/addon/fold/foldgutter.js'
import'codemirror/addon/fold/indent-fold.js'
import'codemirror/addon/fold/markdown-fold.js'
import'codemirror/addon/fold/xml-fold.js'
// 核心样式
import 'codemirror/lib/codemirror.css'

export default {
  name: 'log',
  components: {
    codemirror
  },
  data() {
    return {
      activeName: '0',
      logFiles: [],
      windowHeight: window.innerHeight,
      formInline: {},
      yearList: [],
      dialogShow: false,
      editOptions: {
        tabSize: 4,
        styleActiveLine: true,
        lineNumbers: true,
        styleSelectedText: false,
        line: true,
        foldGutter: true,
        gutters: ["CodeMirror-linenumbers", "CodeMirror-foldgutter"],
        highlightSelectionMatches: { showToken: /\w/, annotateScrollbar: true },
        mode: "text/html",
        // hint.js options
        hintOptions:{
          completeSingle: false
        },
        keyMap: "sublime",
        matchBrackets: true,
        showCursorWhenSelecting: true,
        theme: "monokai",
        extraKeys: { "Ctrl": "autocomplete" },
      },
      logText: '暂无',
      rowCurr: null,
      dialogTitle: '',
      windowHeight: window.innerHeight,
      baseApi: location.origin+'/api'
    }
  },
  methods: {
    handleClick(tab) {
      if (tab.name == '1' ){
       this.getLogFiles()
      } else if (tab.name == '0' ){
      } else if (tab.name == '2' ){
        this.$refs.svnVersion.setIsDataviewLoadStru()
      } else if (tab.name == '3' ){
      }
    },

    //获取文件日志
    getLogFiles(isUserOp, yearFilter){
      if (isUserOp == true) {
        this.utilVue.loadShow(true)
        Object.keys(this.formInline).forEach(key => {
          this.formInline[key] = this.strings.trimrl(this.formInline[key])
        })
      }else {
        yearFilter = ''
      }

      this.logFiles=[]
      this.$ajax.get(`/sys/log/getLogFiles?name=${this.formInline.name}&type=${this.formInline.type}&year=${yearFilter}`).then(response => {
        if (response.code == 0) {
          if (this.yearList.length == 0) {
            let yearListTmp = []
            for(let index in response.data) {
              let year = response.data[index].lastModified.substring(0,4)
              if (!yearListTmp.includes(year)) yearListTmp.push(year)
            }
            yearListTmp.sort((left,right) => {
              return  right-left
            })
            this.yearList = yearListTmp
          }
          this.logFiles = response.data
          if (isUserOp == true) this.utilVue.loadHide()
        }
      })
    },

    //重置
    reset() {
     Object.keys(this.formInline).forEach(key => {
       this.formInline[key] = ''
     })
      this.getLogFiles(true)
    },

    //按钮操作
    btnOp(type, row) {
      console.log('row)', row)
      if (type == 1) {//下载
        var link = document.createElement("a")
        link.setAttribute("href", this.baseApi + '/logs/'+ row.name)
        link.setAttribute("download", row.name.substring(row.name.lastIndexOf('/') + 1))
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
      } else if (type == 2) {//预览
        this.rowCurr = row
        this.logText = '数据加载中，请稍候'
        this.dialogTitle = '日志预览:'+ row.name
        this.dialogShow = true
      } else if (type == 3) {//查看影响记录
        this.utilVue.loadShow(true)
        this.$ajax.get(`/sys/log/getLogFileText?fileName=${this.rowCurr.name}`).then(response => {
          if (response.code == 0) {
            this.logText = response.data.join('\r\n')
            this.$refs.logText.refresh()
            this.utilVue.loadHide()
          }
          this.utilVue.loadHide()
        })
      }
    },

    //Drawer 打开动画结束时的回调
    dialogOpened () {
      this.utilVue.loadShow(true)
      setTimeout(() => {
        this.$ajax.get(`/sys/log/getLogFileText?fileName=${this.rowCurr.name}`).then(response => {
          if (response.code == 0) {
            this.logText = response.data.join('\r\n')
            this.$refs.logText.refresh()
            this.utilVue.loadHide()
          }
        })
      }, 500)
    },

    //扩展按钮事件
    extraButtonClick(para) {
      let buttonKey = para.button.key
      if (buttonKey === 'getLog') { //获取最新日志
        this.getLog(0)
      }else if (buttonKey === 'getLogDelete') { //清空获取最新日志
        this.$confirm('将清空日志重新获取，是否执行？', '系统提示', {
          dangerouslyUseHTMLString: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'success'
        }).then(() => {
          this.getLog(1)
        }).catch(() => {
        })
      }else if (buttonKey === 'copyVersionNum') { //复制所选版本号
        if (!para.data || para.data.length < 1) {
          this.utilMessage.error('请先选中需要复制的记录')
          return
        }

        let versionNumArr = []
        para.data.forEach(row => versionNumArr.push(parseInt(row.versionNum)))
        versionNumArr.sort((left, right) => {
          return left - right
        })

        let msg = `<div>
                         <div   style="word-break: break-all; max-height: 100px; overflow: auto;"><h4 style="height: 33px;">版本号从小到大依次为</h4>
                            <textarea rows="3" cols="20" style=" width: 100%; font-size: 13px; line-height: 13px;border-color: #3a8ee6; outline: none; resize: none;">${versionNumArr.join(',')}</textarea>
                        </div>
                        <div   style="word-break: break-all; max-height: 100px; overflow: auto;"><h4 style="height: 33px;">版本号从大到小依次为</h4>
                            <textarea rows="3" cols="20" style=" width: 100%; font-size: 13px; line-height: 13px;border-color: #3a8ee6; outline: none; resize: none;">${versionNumArr.reverse().join(',')}</textarea>
                        </div>
                    </div>`


        global.utilMessage.alertSuccess(msg);
      }else if (buttonKey === 'copySubmitRemark') { //复制合并所选原始日志
        if (!para.data || para.data.length < 1) {
          this.utilMessage.error('请先选中需要复制的记录')
          return
        }

        let obArr = para.data
        obArr.sort((leftOb, rightOb) => {
          return parseInt(leftOb.versionNum) - parseInt(rightOb.versionNum)
        })
        let msgArr = []

        /**
         日志为以下格式
         子系统类型   可选：spdpc，spdapp，spdfsd
         #分隔符#
         功能分类    基建|主数据|外设|业务|配送|财务|BI|无 【多个,分割】
         #分隔符#
         菜单        菜单名称|无
         #分隔符#
         需求来源    TAPD缺陷|TAPD需求|禅道任务|禅道bug|无
         #分隔符#
         需求来源标识 884|无 【多个,分割】
         #分隔符#
         需求来源链接  需求来源链接|无 【多个,分割】
         #分隔符#
         功能描述      功能描述|无

         svnVersion.setChangeSystem(submitRemarkSplit[0])
         .setChangeType(submitRemarkSplit[1])
         .setChangeMenu(submitRemarkSplit[2])
         .setChangeFrom(submitRemarkSplit[3])
         .setChangeCode(submitRemarkSplit[4])
         .setChangeUrl(submitRemarkSplit[5])
         .setChangeRemark(submitRemarkSplit[6])
         .setChangeValid(true)
         */

        let ChangeSystem=[],ChangeType=[],ChangeMenu=[],ChangeFrom=[],ChangeCode=[],ChangeUrl=[],ChangeRemark=[],ChangeImportance = []
        obArr.forEach(ob => {
          let submitRemark = ob.submitRemark
          let remarkSplit = submitRemark.split('#分隔符#')
          if (remarkSplit != null) {
            if ( remarkSplit.length >= 7) {
              if (!ChangeSystem.includes(this.strings.trimrl(remarkSplit[0]))) ChangeSystem.push(this.strings.trimrl(remarkSplit[0]))
              if (!ChangeType.includes(this.strings.trimrl(remarkSplit[1]))) ChangeType.push(this.strings.trimrl(remarkSplit[1]))
              if (!ChangeMenu.includes(this.strings.trimrl(remarkSplit[2]))) ChangeMenu.push(this.strings.trimrl(remarkSplit[2]))
              if (!ChangeFrom.includes(this.strings.trimrl(remarkSplit[3]))) ChangeFrom.push(this.strings.trimrl(remarkSplit[3]))
              if (!ChangeCode.includes(this.strings.trimrl(remarkSplit[4]))) ChangeCode.push(this.strings.trimrl(remarkSplit[4]))
              if (!ChangeUrl.includes(this.strings.trimrl(remarkSplit[5]))) ChangeUrl.push(this.strings.trimrl(remarkSplit[5]))
              if (!ChangeRemark.includes(this.strings.trimrl(remarkSplit[6]))) ChangeRemark.push('\t#版本号:'+ob.versionNum+'#\n'+this.strings.trimrl(remarkSplit[6]))
            }
            if ( remarkSplit.length >= 8) {
              if (!ChangeImportance.includes(this.strings.trimrl(remarkSplit[7]))) ChangeImportance.push(this.strings.trimrl(remarkSplit[7]))
            }

          } else {
            if (!ChangeRemark.includes(submitRemark)) ChangeRemark.push('\t#版本号:'+ob.versionNum+'#\n'+submitRemark)
          }
        })

        let submitRemarkNew = `
<textarea rows="3" cols="20" style="height: 400px; width: 100%; font-size: 13px; line-height: 13px;border-color: #3a8ee6; outline: none; resize: none;">
\t${ChangeSystem.join(',')}
#分隔符#
\t${ChangeType.join(',')}
#分隔符#
\t${ChangeMenu.join(',')}
#分隔符#
\t${ChangeFrom.join(',')}
#分隔符#
\t${ChangeCode.join(',')}
#分隔符#
\t${ChangeUrl.join(',')}
#分隔符#
${ChangeRemark.join('\n')}
#分隔符#
${ChangeImportance.join(',')}
</textarea>
`
        global.utilMessage.alertSuccess(submitRemarkNew);
      }
    },

    //获取日志
    getLog(clear) {
      this.utilVue.loadShow(true)
      this.$ajax.get(`/svn/version/initSvnVersion?clear=${clear}`).then(response => {
        if (response.code == 0) {
          this.utilMessage.success(response.msg, 5000)
        }
        this.utilVue.loadHide()
        this.$refs.svnVersion.fetchData()
      })
    },

    //新tab打开链接
    openWinOut(url) {
      window.open(url, "_blank");
    },
  },

  computed: {
    //自定义列
    propCustomCols() {
      return [
        {
          name: 'changeUrl',
          title: '需求地址',
          cmode: 'edit',
        },
        {
          name: 'changeImportance',
          title: '重要程度',
          cmode: 'edit',
        }
      ]
    }
  },
}
</script>
